<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ABC口算游戏</title>
    <style>
        /* 全局样式 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: -apple-system, BlinkMacSystemFont, 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
        }
        
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            color: #333;
            overflow-x: hidden;
        }
        
        .container {
            width: 100%;
            max-width: 600px;
            margin: 0 auto;
            padding: 20px;
        }
        
        /* 游戏卡片样式 */
        .game-card {
            background: white;
            border-radius: 20px;
            padding: 30px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
            text-align: center;
            position: relative;
            overflow: hidden;
        }
        
        .game-card::before {
            content: '';
            position: absolute;
            top: -50%;
            left: -50%;
            width: 200%;
            height: 200%;
            background: linear-gradient(45deg, transparent 48%, rgba(255, 255, 255, 0.1) 49%, transparent 50%) repeat;
            animation: shimmer 2s infinite;
            z-index: 0;
        }
        
        @keyframes shimmer {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .card-content {
            position: relative;
            z-index: 1;
        }
        
        /* 标题样式 */
        h1 {
            font-size: 2.5rem;
            color: #ff6b6b;
            margin-bottom: 20px;
            font-weight: bold;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
        }
        
        /* 年级选择样式 */
        .grade-selection {
            margin: 20px 0;
        }
        
        .grade-selection label {
            font-size: 1.2rem;
            margin-right: 10px;
            font-weight: 500;
        }
        
        .grade-selection select {
            padding: 10px 15px;
            font-size: 1rem;
            border: 2px solid #ddd;
            border-radius: 10px;
            outline: none;
            transition: border-color 0.3s;
        }
        
        .grade-selection select:focus {
            border-color: #4ecdc4;
        }
        
        /* 开始按钮样式 */
        .start-btn {
            background: linear-gradient(45deg, #4ecdc4, #44a08d);
            color: white;
            border: none;
            padding: 15px 40px;
            font-size: 1.2rem;
            border-radius: 50px;
            cursor: pointer;
            transition: all 0.3s;
            font-weight: bold;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            margin-top: 20px;
        }
        
        .start-btn:hover {
            transform: translateY(-3px);
            box-shadow: 0 10px 20px rgba(0, 0, 0, 0.15);
        }
        
        .start-btn:active {
            transform: translateY(-1px);
        }
        
        /* 游戏界面样式 */
        .game-screen {
            display: none;
        }
        
        .question-container {
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            padding: 40px;
            border-radius: 15px;
            margin: 20px 0;
            font-size: 2.5rem;
            min-height: 150px;
            display: flex;
            justify-content: center;
            align-items: center;
            box-shadow: inset 0 2px 10px rgba(0, 0, 0, 0.1);
        }
        
        .input-container {
            margin: 20px 0;
        }
        
        .answer-input {
            width: 100%;
            padding: 20px;
            font-size: 1.5rem;
            border: 3px solid #ddd;
            border-radius: 15px;
            outline: none;
            text-align: center;
            transition: border-color 0.3s;
        }
        
        .answer-input:focus {
            border-color: #4ecdc4;
        }
        
        /* 分数输入特殊样式 */
        .fraction-input {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
        }
        
        .fraction-input input {
            width: 80px;
            padding: 15px;
            font-size: 1.5rem;
            border: 3px solid #ddd;
            border-radius: 10px;
            text-align: center;
            outline: none;
        }
        
        .fraction-divider {
            font-size: 2rem;
            margin: 0 10px;
            color: #666;
        }
        
        /* 控制按钮样式 */
        .control-buttons {
            display: flex;
            justify-content: space-between;
            margin-top: 20px;
            gap: 10px;
        }
        
        .control-btn {
            flex: 1;
            padding: 15px;
            font-size: 1rem;
            border: none;
            border-radius: 10px;
            cursor: pointer;
            transition: all 0.3s;
            font-weight: bold;
        }
        
        .submit-btn {
            background: linear-gradient(45deg, #4CAF50, #45a049);
            color: white;
        }
        
        .next-btn {
            background: linear-gradient(45deg, #2196F3, #1976D2);
            color: white;
        }
        
        .control-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
        }
        
        /* 结果反馈样式 */
        .feedback {
            margin: 20px 0;
            padding: 15px;
            border-radius: 10px;
            font-size: 1.2rem;
            display: none;
        }
        
        .feedback.correct {
            background-color: #d4edda;
            color: #155724;
            border: 2px solid #c3e6cb;
            display: block;
        }
        
        .feedback.incorrect {
            background-color: #f8d7da;
            color: #721c24;
            border: 2px solid #f5c6cb;
            display: block;
        }
        
        /* 统计信息样式 */
        .stats {
            display: flex;
            justify-content: space-around;
            margin: 20px 0;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 10px;
        }
        
        .stat-item {
            text-align: center;
        }
        
        .stat-value {
            font-size: 1.8rem;
            font-weight: bold;
            color: #4ecdc4;
        }
        
        .stat-label {
            font-size: 0.9rem;
            color: #666;
            margin-top: 5px;
        }
        
        /* 结束界面样式 */
        .end-screen {
            display: none;
            padding: 20px;
        }
        
        .score-container {
            background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%);
            padding: 30px;
            border-radius: 15px;
            margin: 20px 0;
        }
        
        .final-score {
            font-size: 4rem;
            font-weight: bold;
            color: #ff6b6b;
            margin: 10px 0;
        }
        
        .result-text {
            font-size: 1.5rem;
            margin: 10px 0;
        }
        
        /* 动画效果 */
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .fade-in {
            animation: fadeIn 0.5s ease-out;
        }
        
        /* 响应式设计 */
        @media (max-width: 600px) {
            .container {
                padding: 10px;
            }
            
            .game-card {
                padding: 20px;
            }
            
            h1 {
                font-size: 2rem;
            }
            
            .question-container {
                font-size: 2rem;
                padding: 30px 20px;
            }
            
            .answer-input {
                font-size: 1.3rem;
                padding: 15px;
            }
            
            .fraction-input input {
                width: 60px;
                padding: 10px;
            }
        }
        
        /* 倒计时样式 */
        .timer {
            background: #ff6b6b;
            color: white;
            padding: 10px 20px;
            border-radius: 50px;
            font-size: 1.2rem;
            font-weight: bold;
            margin: 10px auto;
            display: inline-block;
        }
        
        /* 进度条样式 */
        .progress-container {
            width: 100%;
            height: 10px;
            background: #e0e0e0;
            border-radius: 5px;
            margin: 20px 0;
            overflow: hidden;
        }
        
        .progress-bar {
            height: 100%;
            background: linear-gradient(90deg, #4ecdc4, #44a08d);
            width: 0%;
            transition: width 0.3s ease;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="game-card">
            <div class="card-content">
                <!-- 主菜单界面 -->
                <div class="main-menu fade-in">
                    <h1>ABC口算游戏</h1>
                    <p style="font-size: 1.1rem; margin: 20px 0; color: #666;">选择游戏模式</p>
                    
                    <div style="display: flex; flex-direction: column; gap: 15px; margin: 30px 0;">
                        <button class="start-btn" style="font-size: 1.3rem; padding: 20px 40px;" onclick="showSinglePlayerMenu()">单人游戏</button>
                        <button class="start-btn" style="font-size: 1.3rem; padding: 20px 40px; background: linear-gradient(45deg, #ff9a9e 0%, #fecfef 100%);" onclick="window.location.href='static/multiplayer.html'">多人游戏</button>
                    </div>
                </div>
                
                <!-- 单人游戏开始界面 -->
                <div class="start-screen fade-in" style="display: none;">
                    <h1>单人游戏</h1>
                    <p style="font-size: 1.1rem; margin: 20px 0; color: #666;">选择年级和题目数量</p>
                    
                    <div class="grade-selection">
                        <label for="grade">年级：</label>
                        <select id="grade">
                            <option value="1">一年级</option>
                            <option value="2">二年级</option>
                            <option value="3">三年级</option>
                            <option value="4">四年级</option>
                            <option value="5">五年级</option>
                            <option value="6">六年级</option>
                        </select>
                    </div>
                    
                    <div style="margin: 20px 0;">
                        <label for="question-count" style="font-size: 1.1rem; margin-right: 10px; font-weight: 500;">题目数量：</label>
                        <select id="question-count">
                            <option value="10">10题</option>
                            <option value="20">20题</option>
                            <option value="30">30题</option>
                            <option value="50">50题</option>
                        </select>
                    </div>
                    
                    <div style="display: flex; gap: 15px; margin-top: 30px; justify-content: center;">
                        <button class="start-btn" style="flex: 1;" onclick="startGame()">开始游戏</button>
                        <button class="start-btn" style="flex: 1; background: linear-gradient(45deg, #ff9a9e 0%, #fecfef 100%);" onclick="backToMainMenu()">返回</button>
                    </div>
                </div>
                
                <!-- 游戏界面 -->
                <div class="game-screen">
                    <div class="stats">
                        <div class="stat-item">
                            <div class="stat-value" id="correct-count">0</div>
                            <div class="stat-label">正确</div>
                        </div>
                        <div class="stat-item">
                            <div class="stat-value" id="total-count">0</div>
                            <div class="stat-label">总题数</div>
                        </div>
                        <div class="stat-item">
                            <div class="timer" id="timer">60s</div>
                            <div class="stat-label">倒计时</div>
                        </div>
                    </div>
                    
                    <div class="progress-container">
                        <div class="progress-bar" id="progress-bar"></div>
                    </div>
                    
                    <div class="question-container" id="question"></div>
                    
                    <div class="input-container">
                        <input type="text" id="answer" class="answer-input" placeholder="请输入答案" autofocus>
                    </div>
                    
                    <div class="feedback" id="feedback"></div>
                    
                    <div class="control-buttons">
                        <button class="control-btn submit-btn" onclick="submitAnswer()">提交答案</button>
                        <button class="control-btn next-btn" onclick="nextQuestion()">下一题</button>
                    </div>
                </div>
                
                <!-- 结束界面 -->
                <div class="end-screen">
                    <h2>游戏结束！</h2>
                    <div class="score-container">
                        <div class="result-text">你的得分</div>
                        <div class="final-score" id="final-score">0</div>
                        <div class="result-text" id="result-summary"></div>
                    </div>
                    <button class="start-btn" onclick="restartGame()">重新开始</button>
                </div>
            </div>
        </div>
    </div>
    
    <script>
        // 游戏状态
        let gameState = {
            grade: 1,
            totalQuestions: 10,
            currentQuestion: 0,
            correctCount: 0,
            correctAnswer: '',
            timer: null,
            timeLeft: 60,
            isGameOver: false
        };
        
        // 开始游戏
        function startGame() {
            gameState.grade = parseInt(document.getElementById('grade').value);
            gameState.totalQuestions = parseInt(document.getElementById('question-count').value);
            gameState.currentQuestion = 0;
            gameState.correctCount = 0;
            gameState.isGameOver = false;
            gameState.timeLeft = 60;
            
            // 更新UI
            document.getElementById('correct-count').textContent = '0';
            document.getElementById('total-count').textContent = '0';
            document.getElementById('timer').textContent = `${gameState.timeLeft}s`;
            document.getElementById('progress-bar').style.width = '0%';
            document.getElementById('feedback').className = 'feedback';
            
            // 切换屏幕
            document.querySelector('.start-screen').style.display = 'none';
            document.querySelector('.game-screen').style.display = 'block';
            document.querySelector('.end-screen').style.display = 'none';
            
            // 开始计时
            startTimer();
            
            // 生成第一题
            nextQuestion();
        }
        
        // 开始倒计时
        function startTimer() {
            // 清除之前的计时器
            if (gameState.timer) {
                clearInterval(gameState.timer);
            }
            
            gameState.timer = setInterval(() => {
                gameState.timeLeft--;
                document.getElementById('timer').textContent = `${gameState.timeLeft}s`;
                
                // 时间到，结束游戏
                if (gameState.timeLeft <= 0) {
                    endGame();
                }
            }, 1000);
        }
        
        // 获取下一题
        function nextQuestion() {
            // 检查是否完成所有题目
            if (gameState.currentQuestion >= gameState.totalQuestions) {
                endGame();
                return;
            }
            
            const answerInput = document.getElementById('answer');
            const feedback = document.getElementById('feedback');
            const submitButton = document.querySelector('.submit-btn');
            
            // 隐藏反馈
            feedback.className = 'feedback';
            
            // 清空输入框并确保它是可用的
            answerInput.value = '';
            answerInput.disabled = false; // 确保输入框是启用的
            
            // 启用提交按钮
            submitButton.disabled = false;
            submitButton.style.opacity = '1';
            submitButton.style.cursor = 'pointer';
            
            // 请求新题目
            fetch('/api/generate', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ grade: gameState.grade })
            })
            .then(response => response.json())
            .then(data => {
                // 更新题目
                document.getElementById('question').textContent = data.question;
                gameState.correctAnswer = data.answer;
                
                // 更新进度条
                gameState.currentQuestion++;
                document.getElementById('total-count').textContent = gameState.currentQuestion;
                const progress = (gameState.currentQuestion / gameState.totalQuestions) * 100;
                document.getElementById('progress-bar').style.width = `${progress}%`;
                
                // 延迟聚焦，确保DOM更新完成
                setTimeout(() => {
                    answerInput.focus();
                }, 100);
            })
            .catch(error => {
                console.error('获取题目失败:', error);
                alert('获取题目失败，请重试');
            });
        }
        
        // 提交答案
        function submitAnswer() {
            const userAnswer = document.getElementById('answer').value.trim();
            const answerInput = document.getElementById('answer');
            const submitButton = document.querySelector('.submit-btn');
            
            if (!userAnswer) {
                alert('请输入答案');
                return;
            }
            
            // 禁用提交按钮，防止重复提交
            submitButton.disabled = true;
            submitButton.style.opacity = '0.6';
            submitButton.style.cursor = 'not-allowed';
            
            // 验证答案
            fetch('/api/check', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    answer: userAnswer,
                    correct_answer: gameState.correctAnswer
                })
            })
            .then(response => response.json())
            .then(data => {
                const feedback = document.getElementById('feedback');
                
                if (data.correct) {
                    feedback.className = 'feedback correct';
                    feedback.textContent = '正确！太棒了！';
                    gameState.correctCount++;
                    document.getElementById('correct-count').textContent = gameState.correctCount;
                } else {
                    feedback.className = 'feedback incorrect';
                    feedback.textContent = `错误，正确答案是: ${gameState.correctAnswer}`;
                }
                
                // 不直接禁用输入框，而是清空它并重新聚焦
                answerInput.value = '';
                setTimeout(() => {
                    answerInput.focus();
                }, 100);
            })
            .catch(error => {
                console.error('验证答案失败:', error);
                alert('验证答案失败，请重试');
            });
        }
        
        // 结束游戏
        function endGame() {
            // 清除计时器
            if (gameState.timer) {
                clearInterval(gameState.timer);
                gameState.timer = null;
            }
            
            gameState.isGameOver = true;
            
            // 计算得分和正确率
            const score = Math.round((gameState.correctCount / gameState.totalQuestions) * 100);
            const accuracy = Math.round((gameState.correctCount / gameState.totalQuestions) * 100);
            
            // 更新结束界面
            document.getElementById('final-score').textContent = score;
            document.getElementById('result-summary').textContent = 
                `${gameState.correctCount}题正确，${gameState.totalQuestions - gameState.correctCount}题错误，正确率${accuracy}%`;
            
            // 切换屏幕
            document.querySelector('.game-screen').style.display = 'none';
            document.querySelector('.end-screen').style.display = 'block';
        }
        
        // 显示单人游戏菜单
        function showSinglePlayerMenu() {
            document.querySelector('.main-menu').style.display = 'none';
            document.querySelector('.start-screen').style.display = 'block';
        }
        
        // 返回主菜单
        function backToMainMenu() {
            document.querySelector('.start-screen').style.display = 'none';
            document.querySelector('.end-screen').style.display = 'none';
            document.querySelector('.main-menu').style.display = 'block';
        }
        
        // 重新开始游戏
        function restartGame() {
            document.querySelector('.end-screen').style.display = 'none';
            document.querySelector('.main-menu').style.display = 'block';
        }
        
        // 监听回车键提交答案
        document.getElementById('answer').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                // 获取反馈元素以检查是否已有反馈显示
                const feedback = document.getElementById('feedback');
                const hasFeedback = feedback.classList.contains('correct') || feedback.classList.contains('incorrect');
                
                if (this.value.trim()) {
                    // 如果输入框有内容，提交答案
                    submitAnswer();
                } else if (hasFeedback) {
                    // 如果输入框为空且已有反馈，进入下一题
                    nextQuestion();
                }
            }
        });
    </script>
</body>
</html>